/*
 *  script.cpp
 *  Incoming!
 *
 *  Created by Ryan Oldis on 7/25/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 */

#include "script.h"

luaScript* luaScript::_instance = NULL;

luaScript::luaScript()
{
	// Execute the script
	L = lua_open();
	
	
	// start lua
	luaL_openlibs(L);
	
	bindFunctions();
	
}


luaScript* luaScript::Instance()
{
	if (_instance == NULL)
	{
		_instance = new luaScript();
	}
	return _instance;
}

void luaScript::doFile(std::string file)
{
	
	try
	{
		
		luaL_dofile(L, file.c_str());
		
	}
	catch (const std::exception &TheError)
	{
		
		std::cout << TheError.what();
		
	}
}

void luaScript::doString(std::string str)
{
	luaL_dostring(L, str.c_str());
}


void luaScript::mainUpdate()
{
	lua_getglobal(L, "mainUpdate");
	if (lua_pcall(L, 0, 0, 0) != 0)
	{
		//printf("ERROR mainUpdate: You're missing the mainUpdate() lua function that is needed to be called in each frame. Add the mainUpdate() function to main.lua, and re-run the program.\n");
	}
	
}

void luaScript::setVar(std::string var, int i)
{
	lua_pushinteger(L, i);
	lua_setglobal(L, var.c_str());
	//lua_pop(L, 1);
}
void luaScript::setVar(std::string var, float i)
{
	lua_pushnumber(L, i);
	lua_setglobal(L, var.c_str());
	//lua_pop(L, 1);
}
void luaScript::setVar(std::string var, std::string i)
{
	lua_pushstring(L, i.c_str());
	lua_setglobal(L, var.c_str());
	//lua_pop(L, 1);
}



void luaScript::getGlobal(std::string glb)
{
	lua_getglobal(L, glb.c_str());
}

void luaScript::push(int i)
{
	lua_pushinteger(L, i);
}
void luaScript::push(float f)
{
	lua_pushnumber(L, f);
}
void luaScript::push(std::string str)
{
	lua_pushstring(L, str.c_str());
}

bool luaScript::call(int args, int results)
{
	if (lua_pcall(L, args, results, 0) != 0)
	{
		printf("error running function `f': %s", lua_tostring(L, -1));
		return false;
	} else {
		return true;
	}
}

void luaScript::newBlankTable()
{
	lua_newtable(L);
}
void luaScript::setField(const char* key, int i)
{
	lua_pushstring(L, key);
	lua_pushinteger(L, i);
	
	lua_settable(L, -3);
}
void luaScript::setField(const char* key, float i)
{
	lua_pushstring(L, key);
	lua_pushnumber(L, i);
	
	lua_settable(L, -3);
}
void luaScript::setField(const char* key, const char* str)
{
	lua_pushstring(L, key);
	lua_pushstring(L, str);
	
	lua_settable(L, -3);
}


void luaScript::setGlobal(std::string name)
{
	lua_setglobal(L, name.c_str());
}


luaScript::~luaScript()
{
	
	lua_close(L);
	
}